import os
import time
import subprocess
import psutil  # 需要安装：pip install psutil
import webbrowser
import pyautogui


class OpenSoftwares:
    def __init__(self, show_logs=False, show_warnings=False):
        self.show_logs = show_logs
        self.show_warnings = show_warnings

    def open_application(self,app_path, args=None, maximize_window=False):
        try:
            # 检查文件是否存在
            if not os.path.exists(app_path):
                raise FileNotFoundError(f"应用程序路径不存在: {app_path}")
            # 构建启动参数
            command = [app_path]
            if args:
                # 列表和字符串都支持
                if isinstance(args, list):
                    command.extend(args)
                elif isinstance(args, str):
                    command.append(args)
                    
            # 窗口最大化 windowstyle
            if maximize_window and os.name == 'nt':
                command = ["start", "/max", "", *command]
                process = subprocess.Popen(command, shell=True)
            else:
                process = subprocess.Popen(command)
            
            print(f"正在打开: {app_path}")
            if args:
                print(f"启动参数: {args}")
            return process.pid  # 返回进程ID
        except Exception as e:
            print(f"打开应用程序失败: {str(e)}")
            return None

    def close_application(self, process_name):
        """一关就是全关"""
        try:
            # 遍历所有进程
            closed = False
            for proc in psutil.process_iter(['name', 'pid']):
                if proc.info['name'].lower() == process_name.lower():
                    print(f"正在关闭进程: {proc.info['name']} (PID: {proc.info['pid']})")
                    # 尝试优雅关闭
                    proc.terminate()
                    # 等待关闭
                    time.sleep(1)
                    # 如果仍在运行，强制关闭
                    if proc.is_running():
                        time.sleep(1)
                        if proc.is_running():
                            time.sleep(1)
                            if proc.is_running():
                                proc.kill()
                    closed = True
            if not closed:
                print(f"未找到进程: {process_name}")
            return closed
        except Exception as e:
            print(f"关闭应用程序失败: {str(e)}")
            return False

    def open_website_fullscreen(self, url):
        webbrowser.open(url)
        # 等待浏览器启动
        time.sleep(1)
        # 模拟按下F11进入全屏
        pyautogui.press('f11')

    def keymousego(self, script_path, show_logs=False, show_warnings=False):
        """
        执行KeymouseGo脚本
        """
        self.show_logs = show_logs
        self.show_warnings = show_warnings
        if self.show_logs:
            subprocess.run(["python", "KeymouseGo/KeymouseGo.py", script_path], check=True)
        elif self.show_warnings:
            subprocess.run(
                ["python", "KeymouseGo/KeymouseGo.py", script_path],
                check=True,
                stdout=subprocess.DEVNULL,  # 屏蔽标准输出
            )
        else:
            subprocess.run(
                ["python", "KeymouseGo/KeymouseGo.py", script_path],
                check=True,
                stdout=subprocess.DEVNULL,  # 屏蔽标准输出
                stderr=subprocess.DEVNULL   # 屏蔽错误输出
            )


if __name__ == "__main__":
    pass
    